package com.ldw.chapter4.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * <p>Title: CaptchaController</p>
 * <p>Description: </p>
 *
 * @author: dwLiu
 * @date: 2020/3/21 22:58
 */
@Controller
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha.jpg")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        //创建验证码文本
        String createText = captchaProducer.createText();
        //将验证码文本设置到session
        request.getSession().setAttribute("vrifyCode", createText);
        //创建验证码图片
        BufferedImage challenge = captchaProducer.createImage(createText);

        //设置内容类型
        response.setContentType("image/jpeg");
        //获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片验证码数据写到响应输出流
        ImageIO.write(challenge, "jpg", out);
        try {
            out.flush();
        }finally {
            out.close();
        }

    }
}
